<script setup lang='ts'>
import ContractForm from './contract-form.vue'
import { useUserStore } from '@fl/store/modules/user'
import { useAddContract, useAuditContract, useGetContractInfo } from '@fl/api/mall-api'
import { useGetAuthUrl } from '@fl/api/supplier'

const { meta: { isAdmin } } = useRoute()

const authUrlParams = computed(() => ({
    redirectUrl: location.href,
    flag: !isAdmin,
}))

const { data: authUrlData } = useGetAuthUrl(authUrlParams)

const { mutate: addMutate } = useAddContract()

const { mutate: auditMutate } = useAuditContract()

const contractForm = ref<InstanceType<typeof ContractForm> | null>(null)

const { back } = useRouter()

const userStore = useUserStore()

const userInfo = computed(() => userStore.getUserInfo)

const isSupplier = computed(() => userInfo.value?.sysUser?.roles?.[0]?.roleKey === 'supplier')

const { params: { id } } = useRoute()

const { data, isLoading } = useGetContractInfo(ref(id as string), isAdmin)

const queryClient = useQueryClient()
function handleAction(val: any, status: number, onSuccess?: (res: any) => void) {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    addMutate(
        { ...val, status },
        {
            onSuccess: (res) => {
                if (Number(res) === 1) {
                    ElMessageBox.confirm('未授权电子签章', '提示', {
                        confirmButtonText: '去授权',
                        cancelButtonText: '取消',
                        type: 'warning',

                    }).then(() => {
                        if (!unref(authUrlData)?.authUrl) {
                            return
                        }
                        window.open(unref(authUrlData)?.authUrl, '_self')
                    })
                    return
                }
                ElMessage.success('操作成功')
                onSuccess?.(res)
            },
            onSettled: () => {
                loading.close()
            },
        },
    )
}

function handleAudit(val: any, status: number, onSuccess?: (res: any) => void) {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    auditMutate(
        { ...val, status },
        {
            onSuccess: (res) => {
                ElMessage.success('操作成功')
                onSuccess?.(res)
            },
            onError: () => {
                queryClient.invalidateQueries({ queryKey: ['getContractInfo'] })
            },
            onSettled: () => {
                loading.close()
            },
        },
    )
}
function handleSign(val: any) {
    handleAction(val, 0, () => { // 这里接收 res
        contractForm.value!.changeIsFirst()
    })
}
function handleSave(val: any) {
    handleAction(val, 0, back)
}
function handleSubmit(val: any) {
    handleAction(val, 2, back)
}

function handleAuditPass(val: any) {
    handleAudit(val, 1, back)
}
function handleReject(val: any) {
    handleAudit(val, 2, back)
}
</script>

<template>
    <ElSkeleton v-if="isLoading"
                :rows="5"
    />

    <ContractForm v-else
                  ref="contractForm"
                  :is-supplier="isSupplier"
                  :initial-data="data"
                  @save="handleSave"
                  @submit="handleSubmit"
                  @reject="handleReject"
                  @sign="handleSign"
                  @audit-pass="handleAuditPass"
    />
</template>
